var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var loadingMore = false;
var hasMore = true;
var SDKVersion = '';

Page({

  data: {
    util: util,
    ghsData: [],

    authData: '',

    uid: 0,
    token: '',
    picker_arr: [],//picker中range属性值
    picker_index: 0,//picker中value属性值
    id_arr: [],//存储id数组
    result: "",//form提交最终结果
    userV: "",
    phoneV: "",

  },
  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    wx.showLoading({
      title: 'loading',
      mask: 'true'
    });

    var that = this;
    var tc = app.get_tc();
    that.setData({
      tc:tc
    })
    var titlename = tc == -1 ?'Member Management':tc == 1 ? '加盟審核' : '加盟审核';
    wx.setNavigationBarTitle({
      title: titlename,
    });


    hasMore = true;
    page = 1;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('ghs_list/ghs_list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          screen_h:res.windowHeight,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    this.getLoginUserInfo('');
    //读取供货商信息
    that.loadGHS(1);
  },

  getLoginUserInfo: function (inviteuid) {
    var that = this;
    //调用应用实例的方法获取全局数据
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        //更新数据
        that.setData({
          uid: res.uid,
          token: res.token
        })
        that.getVerifiedList(res.uid, res.token);
      } else {
        app.reAuthorize(reGetUserInfo);
        wx.hideLoading();
      }
    }, inviteuid);
  },

  //获取所有用户认证状态
  getVerifiedList: function (uid, token) {
    var that = this;
    var privatekey = utilMd5.hexMD5(uid + 'getVerifiedList' + token);
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getVerifiedList",
        uid: uid,
        catatype: '20',
        privatekey: privatekey
      },
      method: 'GET',
      success: function (responseData) {
        var data = responseData.data;
        console.log("获取所有认证信息：", data);
        if (data && data.res != false ) {
          //更新数据
          that.setData({
            verifiedList: data,
          });
        } else {
          that.setData({
            verifiedList: ''
          });
        }
        
      }
    });
  },


  //下拉选项改变值
  bindPickerChange: function (e) {//选项改变触发事件

    this.setData({
      picker_index: e.detail.value
    })
  },


  ////表单提交触发事件
  formSubmit: function (e) {
    app.saveFormId(e.detail.formId);
    if (this.data.authData && this.data.authData.ispay == '0'){
      wx.redirectTo({
        url: '/pages/join_pay/join_pay?coin=50&authtype=20',
      })
      return;
    }

    var that = this;
    var res = e.detail.value;
    var username = res.username;
    var mobile = res.mobile;
    var invitemobile = res.invitemobile;
    var selector = this.data.id_arr[res.selector];

    if (username == "") {
      var contentname = this.data.tc == 1 ? '姓名不能為空' : '姓名不能为空';
      wx.showModal({
        title: '提示',
        content: contentname,
        showCancel: false,
      })
      return;
    } else if (mobile == "") {
      var contentmobile = this.data.tc == 1 ? '手機號不能為空' : '手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentmobile,
        showCancel: false,
      })
      return;
    } else if (util.orgid == 18681&&invitemobile == "") {
      var contentinvitemobile = this.data.tc == 1 ? '介紹人手機號不能為空' : '介绍人手机号不能为空';
      wx.showModal({
        title: '提示',
        content: contentinvitemobile,
        showCancel: false,
      })
      return;
    } else if (selector == "0" || selector == "") {
      var contentselector = this.data.tc == 1 ? '請選擇供貨商' : '请选择供货商';
      wx.showModal({
        title: '提示',
        content: contentselector,
        showCancel: false,
      })
      return;
    }

    //提交代理商认证请求
    var ac = 'userauth'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'userauth' + that.data.token);
    if (util.orgid == 18681){
      privatekey = utilMd5.hexMD5(that.data.uid + 'userauth2' + that.data.token);
      ac = 'userauth2';
      selector=18681;
    }
    var params = {
      ac: ac,
      uid: that.data.uid,
      realname: username,
      phone: mobile,
      invitephone: invitemobile,
      catatype: "20",
      orgid: selector,
      privatekey: privatekey
    };
    console.log('代理商认证：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("提交代理商申请信息：", responseData);
        if (responseData.data.res == false) {
          wx.showModal({
            title: '提示',
            content: responseData.data.msg,
            showCancel: false,
          })
        } else {
          var contentsucess = this.data.tc == 1 ? '注冊資料已提交' : '注册资料已提交';
           wx.showModal({
            title: '提示',
            content: contentsucess,
            showCancel: false,
            success: function(res){
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/join_pay/join_pay?coin=50&authtype=20',
                })
              }
            }
          })
        }

      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    });
  },


  userNameInput: function (e) {
    this.setData({
      userV: e.detail.value
    })
  },

  userPhoneInput: function (e) {
    this.setData({
      phoneV: e.detail.value
    })
  },
  invitePhoneInput: function (e) {
    this.setData({
      invitephoneV: e.detail.value
    })
  },


  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          if (cpage <= 1) {
            that.setData({
              ghsData: result
            });

          } else {

            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });

          }
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }
        }

        var ghsData = that.data.ghsData;
        var picker_arr = ["请选择"];
        var id_arr = ["0"];
        var sel_index = 0;
        var orgid = '0';
        if (that.data.authData && that.data.authData.orgid){
          orgid = that.data.authData.orgid;
        }
        for (var i = 0; i < ghsData.length; i++) {
          var uid = ghsData[i].uid;
          var username = ghsData[i].username;
          if(uid == orgid){
            sel_index = i + 1;
          }
          picker_arr.push(username);
          id_arr.push(uid);
        }
        that.setData({
          picker_arr: picker_arr,
          id_arr: id_arr,
          picker_index: sel_index,
        });

        wx.hideLoading();

      }
    });
  },
  switchChange:function(e){
    var that=this;
    var tc=that.data.tc
    console.log("switch",e)
    var vid = e.currentTarget.dataset.id;
    var verified=e.detail.value;
    //提交代理商认证请求
    var ac = 'userauthswitch'
    var privatekey = utilMd5.hexMD5(that.data.uid + 'userauthswitch' + that.data.token);
    var params = {
      ac: ac,
      uid: that.data.uid,
      id: vid,
      verified: verified==true?1:0,
      privatekey: privatekey
    };
    console.log('代理商审核：', params);
    // return;

    util.api({
      method: "post",
      data: params,
      success: function (responseData) {
        console.log("审核代理商申请信息：", responseData);
        if (responseData.data.res){
          wx.showToast({
            title: tc == -1 ? 'Success' : tc == 1 ?'成功審核':'成功审核',
          })
        }
        that.getVerifiedList()
      },
      fail: function (e) {
        var contentfail = this.data.tc == 1 ? '網絡異常,請稍候再試' : '网络异常,请稍候再试';
        wx.showModal({
          title: '提示',
          content: contentfail,
          showCancel: false,
        })

      }
    })
  },

  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  showModal: function (e) {
    // 显示遮罩层
    console.log("popup")
    console.log("popup",e.currentTarget.dataset.item);
    var that=this;
    var item = e.currentTarget.dataset.item
    that.setData({
      item: item
    })
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation   

    animation.translate(0, 0).scale3d(0, 0, 0).step()
    this.setData({
      animationData: animation.export(),
      showModal: true,
    })
    setTimeout(function () {
      
      animation.scale3d(1, 1, 1).step()
      animation.translate(0, 0).step()


      this.setData({
        animationData: animation.export(),
        showModal: true,
      })
    }.bind(this), 200)
  },

  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    
    animation.translate(0, 0).scale3d(0, 0, 0).step()

    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      this.setData({
        animationData: animation.export(),
        showModal: false,
      })
    }.bind(this), 200)
  },

})